package com.dong.mvcframework.servlet;

import com.dong.mvcframework.annotations.*;

import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.net.URL;
import java.util.*;

public class ZongDispatcherServlet extends HttpServlet {

    // 用来解析配置文件的工具类
    private Properties contextConfig =  new Properties();

    //扫描的类的缓存
    private List<String> classNameList = new ArrayList<String>();

    //IoC容器，用来缓存实例对象
    private Map<String, Object> ioc = new HashMap<>();

    //保存URL和Method的对应关系
    private Map<String, Method> handleMapping = new HashMap<>();

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        this.doPost(req, resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        try {
            doDispatch(req,resp);
        } catch (Exception e) {
            e.printStackTrace();
            resp.getWriter().write("500 SERVER ERROR");
        }
    }

    private void doDispatch(HttpServletRequest req, HttpServletResponse resp) throws IOException, InvocationTargetException, IllegalAccessException {
        // 初始化结束后，开始处理请求
        // 获取URL
        String url = req.getRequestURI();
        //  获取相对路径
        String contextPath = req.getContextPath();
        url = url.replaceAll(contextPath, "").replaceAll("/+", "/");

        // 处理异常逻辑
        if (!this.handleMapping.containsKey(url)) {
            resp.getWriter().write("404 NOT FOUND");
            return;
        }
        // 获取请求参数map
        // 例：http://localhost:8080/demo?name=123&name=456
        // map：name：{123,456}
        Map<String, String[]> parameterMap = req.getParameterMap();
        Method method = this.handleMapping.get(url);
        String beanName = toLowerFirstCase(method.getDeclaringClass().getSimpleName());
        method.invoke(ioc.get(beanName), req, resp, Arrays.toString(parameterMap.get("name")));
    }

    @Override
    public void init(ServletConfig config) throws ServletException {
        // 1.加载配置文件
        doLoadConfig(config.getInitParameter("contextConfigLocation"));

        // 2.扫描相关的类
        doScanner(contextConfig.getProperty("scanPackage"));

        // 3.初始化所有相关类的实例，并且放入Ioc容器中
        doInstance();

        // 4.完成依赖注入
        doAutowired();

        // 5.初始化HandleMapping
        doInitHandleMapping();

        System.out.println(" spring framework is init");
    }

    /**
     * 初始化HandleMapping
     *
     */
    private void doInitHandleMapping() {
        if (ioc.isEmpty()) {
            return;
        }
        // 循环ioc容器池，寻找controller注解，并解析controller中requestMapping注解
        for (Map.Entry<String, Object> entry : ioc.entrySet()) {
            Class<?> clazz = entry.getValue().getClass();
            if (!clazz.isAnnotationPresent(DongController.class)) {
                continue;
            }
                String baseUrl = "";
            if (clazz.isAnnotationPresent(DongRequestMapping.class)) {
                 baseUrl = clazz.getAnnotation(DongRequestMapping.class).value();
            }
            for (Method method : clazz.getMethods()) {
                if (!method.isAnnotationPresent(DongRequestMapping.class)) {
                    continue;
                }

                DongRequestMapping requestMapping = method.getAnnotation(DongRequestMapping.class);
                // 通过正则表达式将url中的//或多个 替换成/
                String url = ("/" + baseUrl + "/" + requestMapping.value())
                        .replaceAll("/+", "/");
                handleMapping.put(url, method);
                System.out.println("Mapped " + url + " -- " + method);
            }
        }
    }

    /**
     * 依赖注入 再次扫描IOC实例，检查字段（加了注解的）是不是要赋值
     */
    private void doAutowired() {
        if (ioc.isEmpty()) {
            return;
        }
        // public / peotected / private / default
        for (Map.Entry<String, Object> entry : ioc.entrySet()) {

            // 获取字段
            Field[] fields = entry.getValue().getClass().getDeclaredFields();
            for (Field field : fields) {
                if (!field.isAnnotationPresent(DongAutowired.class)) {
                    continue;
                }
                // field 代表 xxxService
                DongAutowired annotation = field.getAnnotation(DongAutowired.class);
                String beanName = annotation.value().trim();
                if ("".equals(beanName)) {
                    // 如果是默认值，则使用类名
                    beanName = field.getType().getName();
                }
                // beanName =  xx.xx.xx.xxService

                // 强制暴力访问的Api
                field.setAccessible(true);
                try {
                    // entry.getValue() 相当于 demoAction（autowired的主类）
                    // demoAction.xxxxService = ioc.get(全路径)
                    field.set(entry.getValue(), ioc.get(beanName));
                } catch (IllegalAccessException e) {
                    e.printStackTrace();
                    continue;
                }
            }
        }
    }

    private void doInstance() {

        // 只有加了注解的类才可以进行初始化

        if (classNameList.isEmpty()) {
            return;
        }
        try {
            for (String className : classNameList) {
                Class<?> clazz = Class.forName(className);
                if (clazz.isAnnotationPresent(DongController.class)) {
                    // 获取类的名称并开始字母小写
                    String simpleName = toLowerFirstCase(clazz.getSimpleName());
                    // 获取类的实例
                    Object instance = clazz.newInstance();
                    // 将名称和实例放进ioc容器中
                    ioc.put(simpleName, instance);
                } else if (clazz.isAnnotationPresent(DongService.class)) {
                    // 获取类的名称并开始字母小写
                    String simpleName = toLowerFirstCase(clazz.getSimpleName());
                    // 不同包下如果存在相同类名，采用自定义的命名
                    DongService annotation = clazz.getAnnotation(DongService.class);

                    if (!"".equals(annotation.value())) {
                        simpleName = annotation.value();
                    }
                    // 获取类的实例
                    Object instance = clazz.newInstance();
                    // 将名称和实例放进ioc容器中
                    ioc.put(simpleName, instance);

                    // 如果使用接口作为属性类型的话，实例化接口对应的实现类
                    for (Class<?> anInterface : clazz.getInterfaces()) {
                        if (ioc.containsKey(anInterface.getName())) {
                            throw new Exception("The bean is exist");
                        }
                        ioc.put(anInterface.getName(),instance);
                    }

                } else {
                    continue;
                }

            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private String toLowerFirstCase(String simpleName) {

        return simpleName.substring(0, 1).toLowerCase() + simpleName.substring(1);
    }


    private void doScanner(String scanPackage) {
        // 将 com.dong 转化为/com/dong/
        URL url = this.getClass().getClassLoader().getResource("/" + scanPackage.replaceAll("\\.", "/"));
        File classPath = new File(url.getFile());
        for (File file : classPath.listFiles()) {

            // 如果不是class文件则需要递归来实现加载类
            if (file.isDirectory()) {
                doScanner(scanPackage + "." + file.getName());
            }else {
                if (!file.getName().endsWith(".class")) {
                    continue;
                }
                // 拿到className的目的是为了，能够利用反射API来进行实例化
                // Class.forName(com.dong.xxx)  // fullClassName
                String className = scanPackage + "." + file.getName().replace(".class", "");
                classNameList.add(className);
            }

        }
    }

    private void doLoadConfig(String contextConfigLocation) {
        InputStream resourceAsStream = this.getClass().getClassLoader().getResourceAsStream(contextConfigLocation);
        try {
            // 读取配置文件的动作
            contextConfig.load(resourceAsStream);
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (null != resourceAsStream) {
                try {
                    resourceAsStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}
